<?php

/**
 * Booking form.
 *
 * @package    playcafebookings
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class BookingForm extends BaseBookingForm
{
    protected $savedCustomValues = null;
    
    public function configure()
    {
        
    }
  
    public function bindWithCustomValues(array $taintedValues, array $taintedFiles, array $customValues) {
        
        // Add the manually calculated dates
        $bookingDatetime = strtotime($customValues['booking_datetime_date'] . ' ' . $customValues['booking_datetime_time']);
        $foodDatetime = strtotime($customValues['booking_datetime_date'] . ' ' . (isset($customValues['food_datetime_time']) ? $customValues['food_datetime_time'] : $customValues['booking_datetime_time']));
        $taintedValues['booking_datetime'] = date('Y-m-d H:i:s', $bookingDatetime);
        $taintedValues['food_datetime'] = date('Y-m-d H:i:s', $foodDatetime);
        
        // Do the bind
        $this->bind($taintedValues, $taintedFiles); 
        
        // Save these values for later - we'll need them in doUpdateObject()
        $this->savedCustomValues = $customValues;
    }
    
    protected function doUpdateObject($values) {
        
        // Do the save
        parent::doUpdateObject($values);
        
        if ($this->savedCustomValues && is_array($this->savedCustomValues)) {
            // Save the party options correctly
            $this->getObject()->encodePartyOptions(
                $this->savedCustomValues['food'],
                $this->savedCustomValues['moreOptions'],
                $this->savedCustomValues['character']
            );
        }
    }
    
    public function show($submitToModule, $showAdminFields = false) {
        ?>
        
<?php use_stylesheets_for_form($this) ?>
<?php use_javascripts_for_form($this) ?>

<?php
    $packages = config('packages');
    $adultPlatters = config('adultPlatters');
    $moreOptions = config('moreOptions');
    $characterCost = config('characterCost');
?>

<script type="text/javascript">
    $(document).ready(function() {
        
        var packages = <?php echo json_encode($packages); ?>;
        var adultPlatters = <?php echo json_encode($adultPlatters); ?>;
        var moreOptions = <?php echo json_encode($moreOptions); ?>;
        var checkingDate = false;
        var dateValid = true;
        
        var updatePrice = function() {
            var totalCost = 0;
            var guestCount = $('#booking_guest_count').val();
            
            var selectedPackage = packages[$('input#booking_party_type').val()];
            totalCost += selectedPackage.priceFlat;
            if ((guestCount - selectedPackage.includedKids) > 0) {
                totalCost += ((guestCount - selectedPackage.includedKids) * selectedPackage.priceExtraKid);
            }
            
            $.each(adultPlatters, function() {
                var count = $('#custom_food_adultPlatters_' + this.id).val();
                totalCost += (count * this.price);
            });
            
            $.each(moreOptions, function() {
                var count = $('#custom_moreOptions_' + this.id).val();
                totalCost += (count * this.price);
            });
            
            var character = $('#custom_character').val();
            if (character) {
                totalCost += <?php echo $characterCost; ?>;
            }
            
            // Give a 10% discount if the party is between 10-2 on a weekday
            var bookingDate = $('#custom_booking_datetime_date').val();
            var bookingTime = $('#custom_booking_datetime_time').val();
            if (bookingDate && bookingTime) {
                var date = $.datepicker.parseDate('yy-mm-dd', bookingDate);
                if (date.getDay() >= 1 && date.getDay() <= 5) {
                    var amPm = getTimePart('#custom_booking_datetime_time', 'amPm');
                    // Parties go for 2 hours...so the party has to either be starting in the morning or right on midday to qualify for the discount
                    if (amPm == 'AM' || bookingTime == '12:00 PM') {
                        totalCost = totalCost - Math.round(0.1 * totalCost);
                    }
                }
            }
            
            var previousTotalCost = $('div.totalCost div.value').html();
            $('div.totalCost div.value').html('$' + totalCost);
            if (previousTotalCost != '$' + totalCost) {
                // The value has changed - highlight the elements to indicate this
                $('div.totalCost').effect('highlight', {color: 'white'}, 1000);
            }
        };
        
        var getTimePart = function(fieldSelector, part) {
            if (part == 'hour' || part == 'minute' || part == 'amPm') {
                if ($(fieldSelector)) {
                    var selectedTime = $(fieldSelector).val();
                    if (selectedTime) {
                        var colonSep = selectedTime.split(':');
                        if (colonSep.length == 2) {
                            if (part == 'hour') {
                                return colonSep[0];
                            }
                            else {
                                var spaceSep = colonSep[1].split(' ');
                                if (spaceSep.length == 2) {
                                    if (part == 'minute') {
                                        return spaceSep[0];
                                    }
                                    else if (part == 'amPm') {
                                        return spaceSep[1];
                                    }
                                }
                            }
                        }
						else {
							var spaceSep = selectedTime.split(' ');
							if (spaceSep.length == 2) {
								if (part == 'hour') {
									return spaceSep[0];
								}
								else if (part == 'amPm') {
									return spaceSep[1];
								}
							}
						}
                    }
                }
            }
            
            return null;
        };
        
        $('input#booking_guest_count').change(updatePrice);
        $('input#booking_guest_count').keyup(updatePrice);
        $('select.adultPlatters').change(updatePrice);
        $('select.moreOptions').change(updatePrice);
        $('select#custom_character').change(updatePrice);
        $('#custom_booking_datetime_date_display').change(updatePrice);
        $('#custom_booking_datetime_time').change(updatePrice);
        
        $('ul.packages li')
            .click(function() {
                $('input#booking_party_type').val($('div.name', this).html());
                var selectedPackage = packages[$('input#booking_party_type').val()];
                
                // Apply the "selected" class to only this package
                $('ul.packages li.selected').removeClass('selected');
                $(this).addClass('selected');
                
                // Show the necessary food options
                var optionTypes = ['mainMeals', 'sweets'];
                $.each(optionTypes, function() {
                    var optionType = this;
                    
                    // Hide them all first
                    $('div.row.' + optionType).hide();
                    $('h2.foodOptions').hide();
                    
                    // Then show the required rows
                    var count = selectedPackage[optionType];
                    for (var i = 1; i <= count; i++) {
                        $('div.row#' + optionType + '_' + i).show();
                    }
                    if (count > 0) {
                        $('h2.foodOptions').show();
                    }
                });
                
                updatePrice();
            });
        
        // Add date picker control
        $('#custom_booking_datetime_date_display').datepicker({
            dateFormat: 'dd/mm/yy',
            altFormat: 'yy-mm-dd',
            altField: '#custom_booking_datetime_date',
            onClose: function(dateText, inst) {
                checkingDate = true;
                $.getJSON('<?php echo url_for($submitToModule . '/checkDate'); ?>?date=' + encodeURIComponent($('#custom_booking_datetime_date').val()), function(data) {
                    dateValid = (data && data.available);
                    checkingDate = false;
                });
            }
        });
        
        // Add time picker controls
        $('#custom_booking_datetime_time').timepicker({
            showMinutes: false,
            showPeriod: true,
            showLeadingZero: false
        });
        $('#custom_food_datetime_time').timepicker({
            showPeriod: true,
            showLeadingZero: false
        });
        
        //
        // Validation
        //
        
        $.validator.addMethod('ageDaysOfWeek', function(value) {
            // Children 8 and under can play any time
            var selectedAge = $('#booking_subject_age').val();
            if (selectedAge <= 8) {
                return true;
            }
            
            // Make sure a date was entered (this should already have been validated)
            var selectedDate = $('#custom_booking_datetime_date_display').datepicker('getDate');
            if (!selectedDate) {
                return false;
            }
            
            // Children over 8 can't book on Saturday or Sunday
            if (selectedDate.getDay() == 0 || selectedDate.getDay() == 6) {
                return false;
            }
            
            // Work out the time & ensure it's after 4pm
            var hour = getTimePart('#custom_booking_datetime_time', 'hour');
            var amPm = getTimePart('#custom_booking_datetime_time', 'amPm');
            if (hour && amPm && amPm == 'PM' && hour >= 4) {
                return true;
            }
            
            return false;
        }, '<?php echo text('validationAgeDaysOfWeek'); ?>');
        
        $.validator.addMethod('foodTiming', function(value) {
            var bookingHour = getTimePart('#custom_booking_datetime_time', 'hour');
            var bookingMinute = getTimePart('#custom_booking_datetime_time', 'minute');
            var bookingAmPm = getTimePart('#custom_booking_datetime_time', 'amPm');
            var foodHour = getTimePart('#custom_food_datetime_time', 'hour');
            var foodMinute = getTimePart('#custom_food_datetime_time', 'minute');
            var foodAmPm = getTimePart('#custom_food_datetime_time', 'amPm');
            
            if (bookingHour && bookingMinute && bookingAmPm && foodHour && foodMinute && foodAmPm) {
                bookingHour += (bookingAmPm == 'PM' ? 12 : 0);
                foodHour += (foodAmPm == 'PM' ? 12 : 0);
                
                var bookingUnixMins = (bookingHour * 60) + bookingMinute;
                var foodUnixMins = (foodHour * 60) + foodMinute;
                
                if ((foodUnixMins - bookingUnixMins) >= 0 && (foodUnixMins - bookingUnixMins) <= 45) {
                    return true;
                }
            }
            
            return false;
        }, '<?php echo text('validationFoodTiming'); ?>');
        
        $.validator.addMethod('dateAvailable', function(value) {
            if (checkingDate) {
                // Don't want the user to be held up wile waiting for a response
                return true;
            }
            else {
                return dateValid;
            }
        }, '<?php echo text('validationDateAvailable'); ?>');

        $.validator.addMethod('timeSunday', function(value) {
            // Make sure a date was entered (this should already have been validated)
            var selectedDate = $('#custom_booking_datetime_date_display').datepicker('getDate');
            if (!selectedDate) {
                return false;
            }
            
            // Is it even a Sunday?
            if (selectedDate.getDay() != 0) {
                return true;
            }
            
            // Work out the time & ensure it's after 12.30
            var hour = getTimePart('#custom_booking_datetime_time', 'hour');
            var amPm = getTimePart('#custom_booking_datetime_time', 'amPm');
            if (hour && amPm && amPm == 'PM' && hour >= 1) {
                return true;
            }
            
            return false;
        }, '<?php echo text('validationTimeSunday'); ?>');
        
        $("form#booking").validate({
            rules: {
                "booking[guest_count]": {
                    required: true,
                    digits: true,
                    min: 2
                },
                <?php if ($showAdminFields == false) { // Admins can veto the datetime-based rules ?>
                    "custom[booking_datetime_date]": {
                        required: true,
                        dateAvailable: true
                    },
                    "custom[booking_datetime_time]": {
                        required: true,
                        ageDaysOfWeek: true,
						timeSunday: true
                    },
                <?php } ?>
                //"custom[food_datetime_time]": {
                //    required: true,
                //    foodTiming: true
                //},
                "booking[contact_firstname]": {
                    required: true
                },
                "booking[contact_lastname]": {
                    required: true
                },
                "booking[contact_phone]": {
                    required: true,
                    digits: true
                },
                "booking[contact_email]": {
                    required: false,
                    email: true
                },
                "booking[subject_firstname]": {
                    required: true
                },
                "booking[subject_lastname]": {
                    required: true
                },
            }
        });
        
        // Finally, set the starting values
        <?php if (!$this->getObject()->isNew()) { ?>
            // Select the saved package
            $('ul.packages li#package_<?php echo $this->getObject()->getPartyType() ?>').click();
            
            <?php
                $options = $this->getObject()->decodePartyOptions();
                
                foreach (array('mainMeals', 'sweets', 'adultPlatters') as $foodOptionType) {
                    foreach ($options['food'][$foodOptionType] as $id => $food) {
                        echo "$('#custom_food_" . $foodOptionType . "_" . $id . "').val('" . $food . "');" . PHP_EOL;
                    }
                }
                
                foreach ($options['moreOptions'] as $id => $option) {
                    echo "$('#custom_moreOptions_" . $id . "').val('" . $option . "');" . PHP_EOL;
                }
                
                if ($options['character']) {
                    echo "$('#custom_character').val('" . $options['character'] . "');" . PHP_EOL;
                }
            ?>
            
            $('#custom_booking_datetime_date_display').val('<?php echo date('d/m/Y', strtotime($this->getObject()->getBookingDatetime())) ?>');
            $('#custom_booking_datetime_date').val('<?php echo date('Y-m-d', strtotime($this->getObject()->getBookingDatetime())) ?>');
            
            $('#custom_booking_datetime_time').val('<?php echo date('g:i A', strtotime($this->getObject()->getBookingDatetime())) ?>');
            $('#custom_food_datetime_time').val('<?php echo date('g:i A', strtotime($this->getObject()->getFoodDatetime())) ?>');
            
            $('#booking_room').val('<?php echo $this->getObject()->getRoom() ?>');
            
            updatePrice();
        <?php } else { ?>
            // Select the first package by default
            $('ul.packages li').first().click();
        <?php } ?>
    });
</script>

<form id="booking" action="<?php echo url_for($submitToModule.'/'.($this->getObject()->isNew() ? 'create' : 'update').(!$this->getObject()->isNew() ? '?id='.$this->getObject()->getId() : '')) ?>" method="post" <?php $this->isMultipart() and print 'enctype="multipart/form-data" ' ?>>
    <?php if (!$this->getObject()->isNew()): ?>
        <input type="hidden" name="sf_method" value="put" />
        <input type="hidden" name="booking[amount_paid]" value="<?php echo $this->getObject()->getAmountPaid(); ?>" />
        <input type="hidden" name="booking[status]" value="<?php echo $this->getObject()->getStatus(); ?>" />
    <?php endif; ?>
    
    <div class="section">
        <div class="sectionBody">
    
            <ul class="packages">
                <input type="hidden" id="booking_party_type" name="booking[party_type]" value="SuperSavings" />
                <?php
                    foreach ($packages as $packageName => $package) {
                        ?>
                            <li id="package_<?php echo $packageName; ?>">
                                <div class="name"><?php echo $packageName; ?></div>
                                <div class="description"><?php echo text($package['description']); ?></div>
                                <div class="price"><?php echo text('packagePrice', array(
                                                                                        'priceFlat' => $package['priceFlat'],
                                                                                        'priceExtraKid' => $package['priceExtraKid'],
                                                                                        'includedKids' => $package['includedKids']
                                                                                    )); ?></div>
                            </li>
                        <?php
                    }
                ?>
                <div class="clear"></div>
            </ul>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelGuestCount'); ?></span></div>
                <div class="field">
                    <?php echo $this['guest_count']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
        
        </div>
    </div>
    
    <div class="row totalCost">
        <div class="label"><span class="title"><?php echo text('totalCost'); ?></span></div>
        <div class="value">$0</div>
        <div class="clear"></div>
    </div>
    
    <div class="section">
    
        <h2 class="foodOptions"><?php echo text('headingFoodOptions'); ?></h2>
        
        <div class="sectionBody">
            
            <?php
                function printFoodLists($foodList, $type, $count) {
                    $defaultOption = 0;
                    
                    for ($i = 1; $i <= $count; $i++) {
                        ?>
                            <div class="row <?php echo $type; ?>" id="<?php echo $type . '_' . $i; ?>" style="display: none;">
                                <div class="label"><span class="title"><?php echo text($type, array('number' => $i)); ?></span></div>
                                <div class="field">
                                    <select id="custom_food_<?php echo $type . '_' . $i; ?>" name="custom[food]<?php echo '[' . $type . '][' . $i . ']'; ?>">
                                        <?php
                                            $selected = $foodList[$defaultOption];
                                            foreach ($foodList as $food) {
                                                echo "<option" . ($food == $selected ? " selected" : "") . ">" . $food . "</option>" . PHP_EOL;
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div class="clear"></div>
                            </div>
                        <?php
                        $defaultOption++;
                    }
                }
            
                $kidSavouryFood = config('kidSavouryFood');
                $maxMainMeals = config('maxMainMeals');
                printFoodLists($kidSavouryFood, 'mainMeals', $maxMainMeals);
                
                $kidSweetFood = config('kidSweetFood');
                $maxSweets = config('maxSweets');
                printFoodLists($kidSweetFood, 'sweets', $maxSweets);
            ?>
        
        </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingAdultPlatters'); ?></h2>
        <div class="hint"><?php echo text('adultPlattersExtraText'); ?></div>
        
        <div class="sectionBody">
    
            <?php
                foreach ($adultPlatters as $adultPlatter) {
                    ?>
                        <div class="row">
                            <div class="label">
                                <span class="title"><?php echo $adultPlatter['name'] . " (+$" . $adultPlatter['price'] . ")"; ?></span>
                                <span class="hint"><?php echo $adultPlatter['extraText']; ?></span>
                            </div>
                            <div class="field">
                                <select class="adultPlatters" id="custom_food_adultPlatters_<?php echo $adultPlatter['id']; ?>" name="custom[food][adultPlatters][<?php echo $adultPlatter['id']; ?>]">
                                    <?php
                                        for ($i = 0; $i <= 6; $i++) {
                                            echo "<option>" . $i . "</option>" . PHP_EOL;
                                        }
                                    ?>
                                </select>
                            </div>
                            <div class="clear"></div>
                        </div>
                    <?php
                }
            ?>
        
        </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingMoreOptions'); ?></h2>
        
        <div class="sectionBody">
        
            <?php
                foreach ($moreOptions as $option) {
                    ?>
                        <div class="row">
                            <div class="label">
                                <span class="title"><?php echo $option['name'] . " (+$" . $option['price'] . ")"; ?></span>
                                <span class="hint"><?php echo $option['extraText']; ?></span>
                            </div>
                            <div class="field">
                                <select class="moreOptions" id="custom_moreOptions_<?php echo $option['id']; ?>" name="custom[moreOptions][<?php echo $option['id']; ?>]">
                                    <?php
                                        for ($i = 0; $i <= 4; $i++) {
                                            echo "<option>" . $i . "</option>" . PHP_EOL;
                                        }
                                    ?>
                                </select>
                            </div>
                            <div class="clear"></div>
                        </div>
                    <?php
                }
            ?>
        
        </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingCharacters'); ?></h2>
        
        <div class="sectionBody">
        
            <div class="comments"><?php echo text('charactersDetails'); ?></div>
    
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelCharacter') . " (+$" . $characterCost . ")"; ?></span></div>
                <div class="field">
                    <select id="custom_character" name="custom[character]">
                        <option value=""><?php echo text('optionNoCharacter'); ?></option>
                        <?php
                            $characters = config('characters');
                            foreach ($characters as $character) {
                                echo "<option>" . $character . "</option>" . PHP_EOL;
                            }
                        ?>
                    </select>
                </div>
                <div class="clear"></div>
            </div>
        
        </div>
    </div>
    
    <div class="row totalCost">
        <div class="label"><span class="title"><?php echo text('totalCost'); ?></span></div>
        <div class="value">$0</div>
        <div class="clear"></div>
    </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingBirthdayBoyGirlDetails'); ?></h2>
        
        <div class="sectionBody">
  
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelSubjectFirstname'); ?></span></div>
                <div class="field">
                    <?php echo $this['subject_firstname']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelSubjectLastname'); ?></span></div>
                <div class="field">
                    <?php echo $this['subject_lastname']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelSubjectGender'); ?></span></div>
                <div class="field">
                    <?php echo $this['subject_gender']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label">
                    <span class="title"><?php echo text('labelSubjectAge'); ?></span>
                    <span class="hint"><?php echo text('hintSubjectAge'); ?></span>
                </div>
                <div class="field">
                    <select id="booking_subject_age" name="booking[subject_age]">
                        <?php
                            for ($i = 1; $i <= 11; $i++) {
                                echo "<option>" . $i . "</option>" . PHP_EOL;
                            }
                        ?>
                    </select>
                </div>
                <div class="clear"></div>
            </div>
        
        </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingPartyDetails'); ?></h2>
        
        <div class="sectionBody">
      
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelDate'); ?></span></div>
                <div class="field">
                    <input type="text" id="custom_booking_datetime_date_display" />
                    <input type="hidden" id="custom_booking_datetime_date" name="custom[booking_datetime_date]" />
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label">
                    <span class="title"><?php echo text('labelArrivalTime'); ?></span>
                    <span class="hint"><?php echo text('hintArrivalTime'); ?></span>
                </div>
                <div class="field">
                    <input type="text" id="custom_booking_datetime_time" name="custom[booking_datetime_time]" value="10:00 AM" />
                </div>
                <div class="clear"></div>
            </div>
          
            <?php if ($showAdminFields) { ?>
                <div class="row">
                    <div class="label">
                        <span class="title"><?php echo text('labelFoodTime'); ?></span>
                        <span class="hint"><?php echo text('hintFoodTime'); ?></span>
                    </div>
                    <div class="field">
                        <input type="text" id="custom_food_datetime_time" name="custom[food_datetime_time]" value="10:30 AM" />
                    </div>
                    <div class="clear"></div>
                </div>
  
                <div class="row">
                    <div class="label"><span class="title"><?php echo text('labelRoom'); ?></span></div>
                    <div class="field">
                        <select name="booking[room]" id="booking_room">
                            <?php
                                foreach (config('rooms') as $room) {
                                    echo "<option>" . $room . "</option>" . PHP_EOL;
                                }
                            ?>
                        </select>
                    </div>
                    <div class="clear"></div>
                </div>
            <?php } ?>
        
        </div>
    </div>
    
    <div class="section">
    
        <h2><?php echo text('headingContactDetails'); ?></h2>
        
        <div class="sectionBody">
  
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelContactFirstname'); ?></span></div>
                <div class="field">
                    <?php echo $this['contact_firstname']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelContactLastname'); ?></span></div>
                <div class="field">
                    <?php echo $this['contact_lastname']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelContactPhone'); ?></span></div>
                <div class="field">
                    <?php echo $this['contact_phone']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
          
            <div class="row">
                <div class="label"><span class="title"><?php echo text('labelContactEmail'); ?></span></div>
                <div class="field">
                    <?php echo $this['contact_email']->render(); ?>
                </div>
                <div class="clear"></div>
            </div>
        
        </div>
    </div>
    
    <?php if ($showAdminFields) { ?>
        <div class="section">
    
            <h2><?php echo text('headingOther'); ?></h2>
            
            <div class="sectionBody">
      
                <div class="row">
                    <div class="label"><span class="title"><?php echo text('labelNotes'); ?></span></div>
                    <div class="field">
                        <?php echo $this['notes']->render(); ?>
                    </div>
                    <div class="clear"></div>
                </div>
            
            </div>
        </div>
    <?php } ?>
  
    <input class="submit" type="submit" value="Save" />
    
    <?php echo $this['_csrf_token']->render(); ?>
    
</form>

        <?php
    }
}
